package servlet;

import service.ArticleService;
import util.SessionUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 发布文章Servlet
 */
@WebServlet("/publish")
public class PublishArticleServlet extends HttpServlet {
    private ArticleService articleService = new ArticleService();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        // 检查登录状态
        Integer userId = SessionUtils.getCurrentUserId(request);
        if (userId == null) {
            response.sendRedirect("login.html");
            return;
        }

        try {
            String title = request.getParameter("title");
            String content = request.getParameter("content");

            System.out.println("发布文章 - 标题: " + title + ", 用户ID: " + userId);

            // 参数校验
            if (title == null || title.trim().isEmpty() ||
                    content == null || content.trim().isEmpty()) {
                response.getWriter().println("<script>alert('标题和内容不能为空');history.back();</script>");
                return;
            }

            // 发布文章
            boolean isPublished = articleService.publish(title, content, userId);

            if (isPublished) {
                response.sendRedirect("articleList");
            } else {
                response.getWriter().println("<script>alert('发布失败，请重试');history.back();</script>");
            }

        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().println("<script>alert('系统错误，请稍后重试');history.back();</script>");
        }
    }
}